require'digest/sha2'
class User <ActiveRecord::Base
  validates :email, :presence => true, :uniqueness => true
  validates :password ,:confirmation => true
  attr_accessor :password_confirmation
  attr_reader :password
  validate :password_must_be_present

  #function: using for reseting password
  def User.reset(body_mail) #default: 123
    @body = body_mail
    @user = User.find_by_email(@body["mail"])
    @user.update_attributes(:hashed_password=>"7d30d83a42c181823c30b32d62ad8d97b278c22ca4da33979bf58cbbb93a4f3a", :salt=>"281482200.9447045660917708")
  end


  def self.search(search)
    if search
      a = find(:all, :conditions => ['users.firstName LIKE ? OR users.lastName LIKE ?', "%#{search}%", "%#{search}%"])
    else
      find(:all)
    end
  end

  def User.authenticate(email, password)
    if user = find_by_email(email)
      if user.hashed_password == encrypt_password(password, user.salt)
      user
      end
    end
  end

  def User.encrypt_password(password, salt)
    Digest::SHA2.hexdigest(password + "wibble" + salt)
  end

  def password=(password)
    @password = password
     if password.present?
       generate_salt
       self.hashed_password = self.class.encrypt_password(password, salt)
     end
  end

private
  def password_must_be_present
     errors.add(:password, "Missing password") unless hashed_password.present?
  end
  def generate_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
end